{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.impute import SimpleImputer\n",
    "from sklearn.preprocessing import OneHotEncoder, Binarizer, MinMaxScaler\n",
    "from sklearn.compose import ColumnTransformer\n",
    "from sklearn.feature_selection import SelectKBest, chi2\n",
    "from sklearn.decomposition import PCA\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.preprocessing import FunctionTransformer\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义列变换器：对不同列应用不同的预处理\n",
    "preprocessor = ColumnTransformer(\n",
    "    transformers=[\n",
    "        ('onehot', OneHotEncoder(sparse_output=False), [0]),        # 对第0列进行独热编码\n",
    "        ('log', FunctionTransformer(np.log1p), [1, 2, 3]),           # 对第1-3列进行对数变换\n",
    "        ('binary', Binarizer(), [4])                                  # 对第4列进行二值化\n",
    "    ],\n",
    "    remainder='passthrough'  # 其余列保持不变\n",
    ")\n",
    "\n",
    "# 构建完整的流水线\n",
    "pipeline = Pipeline(steps=[\n",
    "    ('imputer', SimpleImputer(strategy='mean')),         # 缺失值填充\n",
    "    ('preprocessor', preprocessor),                      # 列变换\n",
    "    ('scaler', MinMaxScaler()),                           # 特征缩放\n",
    "    ('feature_selection', SelectKBest(chi2, k=3)),        # 特征选择\n",
    "    ('pca', PCA(n_components=2)),                         # PCA降维\n",
    "    ('classifier', LogisticRegression(penalty='l2'))      # 逻辑回归分类器\n",
    "])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预测结果: [0 1 0]\n"
     ]
    }
   ],
   "source": [
    "# 示例数据（5列特征）\n",
    "X = np.array([\n",
    "    [1, 10, 20, 30, 0.5],\n",
    "    [2, 15, 25, 35, 0.7],\n",
    "    [1, 5, 15, 25, 0.3],\n",
    "])\n",
    "\n",
    "y = np.array([0, 1, 0])  # 标签\n",
    "\n",
    "# 训练模型\n",
    "pipeline.fit(X, y)\n",
    "\n",
    "# 预测\n",
    "y_pred = pipeline.predict(X)\n",
    "print(\"预测结果:\", y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以Stpe的形式表达"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 步骤1：缺失值处理\n",
    "step1 = ('imputer', SimpleImputer(strategy='mean'))\n",
    "\n",
    "# 步骤2：列变换（替代 FeatureUnionExt）\n",
    "step2_1 = ('onehot', OneHotEncoder(sparse_output=False), [0])  # 对第0列进行独热编码\n",
    "step2_2 = ('log', FunctionTransformer(np.log1p), [1, 2, 3])     # 对第1-3列进行对数变换\n",
    "step2_3 = ('binary', Binarizer(), [4])                            # 对第4列进行二值化\n",
    "\n",
    "preprocessor = ColumnTransformer(\n",
    "    transformers=[step2_1, step2_2, step2_3],\n",
    "    remainder='passthrough'  # 其余列保持不变\n",
    ")\n",
    "\n",
    "step2 = ('preprocessor', preprocessor)\n",
    "\n",
    "# 步骤3：特征缩放\n",
    "step3 = ('scaler', MinMaxScaler())\n",
    "\n",
    "# 步骤4：特征选择\n",
    "step4 = ('feature_selection', SelectKBest(chi2, k=3))\n",
    "\n",
    "# 步骤5：PCA降维\n",
    "step5 = ('pca', PCA(n_components=2))\n",
    "\n",
    "# 步骤6：逻辑回归分类器\n",
    "step6 = ('classifier', LogisticRegression(penalty='l2'))\n",
    "\n",
    "# 构建完整的流水线\n",
    "pipeline_with_step_style = Pipeline(steps=[step1, step2, step3, step4, step5, step6])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "my_env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
